package com.shine.app.ui;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.shine.app.BaseActivity;
import com.shine.app.R;
import com.shine.app.adapter.CalendarAdapter;
import com.shine.app.commons.Calendars;
import com.shine.app.commons.SpecialCalendar;
import com.shine.app.commons.StringUtils;

public class CalendarActivity extends BaseActivity {

	protected GestureDetector gestureDetector = null;
	protected CalendarAdapter calendarAdapter = null;
	protected SpecialCalendar specialCalendar = null;
	protected ViewFlipper flipper = null;
	protected GridView gridView = null;
	protected static int jumpMonth = 0;
	protected static int jumpYear = 0;
	protected int currentYear = 0;
	protected int currentMonth = 0;
	protected int currentDay = 0;
	protected String currentDate = "";
	protected int gvFlag = 0;

	protected TextView previousMonthTextView;
	protected TextView currentMonthTextView;
	protected TextView nextMonthTextView;
	protected TextView dateTextView;
	protected ImageView search_date_imageView;
	protected LinearLayout search_date;
	protected LinearLayout layout_date;
	protected ImageView previousImageView;
	protected ImageView nextImageView;

	protected int selectYear;
	protected int selectMonth;
	protected int selectDay;

	protected int temporaryYear;
	protected int temporaryMonth;
	protected int temporaryDay;

	public CalendarActivity() {
	}

	protected void initCalendarView() {
		currentMonthTextView = (TextView) findViewById(R.id.currentMonth);
		previousMonthTextView = (TextView) findViewById(R.id.previousMonth);
		nextMonthTextView = (TextView) findViewById(R.id.nextMonth);
		previousMonthTextView.setTextColor(Color.LTGRAY);
		nextMonthTextView.setTextColor(Color.LTGRAY);
		dateTextView = (TextView) this.findViewById(R.id.text_date);
		search_date_imageView = (ImageView) this
				.findViewById(R.id.search_date_image);
		search_date_imageView.setTag(false);
		search_date = (LinearLayout) this.findViewById(R.id.search_date);
		layout_date = (LinearLayout) this.findViewById(R.id.layout_date);
		previousImageView = (ImageView) this.findViewById(R.id.pre);
		nextImageView = (ImageView) this.findViewById(R.id.next);
		previousImageView.setOnClickListener(new SelectDate(false));
		nextImageView.setOnClickListener(new SelectDate(true));
		gestureDetector = new GestureDetector(this, new MyGestureListener());
		flipper = (ViewFlipper) findViewById(R.id.flipper);
		flipper.removeAllViews();
	}

	protected void initCalendarDate(String input) {
		specialCalendar = new SpecialCalendar();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
		currentDate = sdf.format(new Date());
		currentYear = Integer.parseInt(currentDate.split("-")[0]);
		currentMonth = Integer.parseInt(currentDate.split("-")[1]);
		currentDay = Integer.parseInt(currentDate.split("-")[2]);

		if (!StringUtils.isEmpty(input)) {
			String[] days = input.split("/");
			selectYear = Integer.parseInt(days[2]);
			selectMonth = Integer.parseInt(days[0]);
			selectDay = Integer.parseInt(days[1]);
		} else {
			int daysOfMonth = specialCalendar.getDaysOfMonth(
					specialCalendar.isLeapYear(currentYear), currentMonth);
			if (daysOfMonth == currentDay) {
				if (currentMonth == 12) {
					selectYear = currentYear + 1;
					selectMonth = 1;
					selectDay = 1;
				} else {
					selectYear = currentYear;
					selectMonth = currentMonth + 1;
					selectDay = 1;
				}
			} else {
				selectYear = currentYear;
				selectMonth = currentMonth;
				selectDay = currentDay + 1;
			}
		}
		temporaryYear = selectYear;
		temporaryMonth = selectMonth;
		temporaryDay = selectDay;
	}

	protected void initCalendarDateView() {
		calendarAdapter = new CalendarAdapter(this, jumpMonth, jumpYear,
				currentYear, currentMonth, currentDay, selectYear, selectMonth,
				selectDay);
		addGridView();
		gridView.setAdapter(calendarAdapter);
		flipper.addView(gridView, 0);
		addTextToTopTextView();
		String result = selectMonth + "/" + selectDay + "/" + selectYear;
		dateTextView.setText(Calendars.getInstance().format(result));
	}

	public class MyGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			int gvFlag = 0;
			if (e1.getX() - e2.getX() > 120) {
				enterNextMonth(gvFlag);
				return true;
			} else if (e1.getX() - e2.getX() < -120) {
				enterPrevMonth(gvFlag);
				return true;
			}
			return false;
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		this.gestureDetector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}

	protected void enterNextMonth(int gvFlag) {
		addGridView();
		jumpMonth++;
		calendarAdapter = new CalendarAdapter(this, jumpMonth, jumpYear,
				currentYear, currentMonth, currentDay, selectYear, selectMonth,
				selectDay);
		gridView.setAdapter(calendarAdapter);
		addTextToTopTextView();
		gvFlag++;
		flipper.addView(gridView, gvFlag);
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_out));
		flipper.showNext();
		flipper.removeViewAt(0);
	}

	protected void enterPrevMonth(int gvFlag) {
		addGridView();
		jumpMonth--;
		calendarAdapter = new CalendarAdapter(this, jumpMonth, jumpYear,
				currentYear, currentMonth, currentDay, selectYear, selectMonth,
				selectDay);
		gridView.setAdapter(calendarAdapter);
		gvFlag++;
		addTextToTopTextView();
		flipper.addView(gridView, gvFlag);
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_out));
		flipper.showPrevious();
		flipper.removeViewAt(0);
	}

	public void addTextToTopTextView() {
		int year = Integer.parseInt(calendarAdapter.getShowYear());
		int month = Integer.parseInt(calendarAdapter.getShowMonth());
		int previousYear;
		int previousMonth;
		int nextYear;
		int nextMonth;
		if (month == 1) {
			previousYear = year - 1;
			previousMonth = 12;
		} else {
			previousYear = year;
			previousMonth = month - 1;
		}
		if (month == 12) {
			nextYear = year + 1;
			nextMonth = 1;
		} else {
			nextYear = year;
			nextMonth = month + 1;
		}
		previousMonthTextView.setText(new StringBuffer(
				convertMonth(previousMonth)).append(" ").append(previousYear)
				.append("\t").toString().trim());
		currentMonthTextView.setText(new StringBuffer(convertMonth(month))
				.append(" ").append(year).append("\t").toString().trim());
		nextMonthTextView.setText(new StringBuffer(convertMonth(nextMonth))
				.append(" ").append(nextYear).append("\t").toString().trim());
	}

	protected void addGridView() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int Width = display.getWidth();
		int Height = display.getHeight();

		gridView = new GridView(this);
		gridView.setNumColumns(7);
		gridView.setColumnWidth(40);
		if (Width == 720 && Height == 1280) {
			gridView.setColumnWidth(40);
		}
		gridView.setGravity(Gravity.CENTER_VERTICAL);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setVerticalSpacing(1);
		gridView.setHorizontalSpacing(1);
		gridView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return CalendarActivity.this.gestureDetector
						.onTouchEvent(event);
			}
		});

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				TextView dayText = (TextView) view.findViewById(R.id.tv_day);
				if ((Boolean) dayText.getTag()) {
					temporaryDay = Integer.parseInt(calendarAdapter
							.getDateByClickItem(position));
					temporaryYear = Integer.parseInt(calendarAdapter
							.getShowYear());
					temporaryMonth = Integer.parseInt(calendarAdapter
							.getShowMonth());
					calendarAdapter.setSelectYear(temporaryYear);
					calendarAdapter.setSelectMonth(temporaryMonth);
					calendarAdapter.setSelectDay(temporaryDay);
					calendarAdapter.notifyDataSetChanged();
				}
			}
		});
		gridView.setLayoutParams(params);
	}

	public class SelectDate implements OnClickListener {
		boolean flag = false;

		public SelectDate() {
		}

		public SelectDate(Boolean mark) {
			this.flag = mark;
		}

		@Override
		public void onClick(View v) {
			if (flag) {
				selectYear = temporaryYear;
				selectMonth = temporaryMonth;
				selectDay = temporaryDay;
			} else {
				temporaryYear = selectYear;
				temporaryMonth = selectMonth;
				temporaryDay = selectDay;
			}
			setCalendarDate();
		}
	}

	protected void setCalendarDate() {
		String result = selectMonth + "/" + selectDay + "/" + selectYear;
		result = Calendars.getInstance().format(result);
		dateTextView.setText(result);
		layout_date.setVisibility(View.GONE);
		search_date_imageView.setTag(false);
		search_date_imageView.setImageResource(R.drawable.searchlocation_below);
		calendarAdapter.setSelectYear(selectYear);
		calendarAdapter.setSelectMonth(selectMonth);
		calendarAdapter.setSelectDay(selectDay);
		calendarAdapter.notifyDataSetChanged();
	}

	protected String convertMonth(int month) {
		String result = "";
		Resources resources = this.getResources();
		switch (month) {
		case 1:
			result = resources.getString(R.string.january);
			break;
		case 2:
			result = resources.getString(R.string.february);
			break;
		case 3:
			result = resources.getString(R.string.march);
			break;
		case 4:
			result = resources.getString(R.string.april);
			break;
		case 5:
			result = resources.getString(R.string.may);
			break;
		case 6:
			result = resources.getString(R.string.june);
			break;
		case 7:
			result = resources.getString(R.string.july);
			break;
		case 8:
			result = resources.getString(R.string.august);
			break;
		case 9:
			result = resources.getString(R.string.september);
			break;
		case 10:
			result = resources.getString(R.string.october);
			break;
		case 11:
			result = resources.getString(R.string.november);
			break;
		case 12:
			result = resources.getString(R.string.december);
			break;
		default:
			result = String.valueOf(month);
			break;
		}
		return result;
	}
}